using System.Text;
using NUnit.Framework;
using NUnit.Framework.Constraints;

namespace ObjectinatorTests
{
    public class EqualIgnoringWhitespaceConstraint : Constraint
    {
        private readonly string expected;

        public EqualIgnoringWhitespaceConstraint(string expected)
        {
            this.expected = expected;
        }

        public override bool Matches(object actual)
        {
            this.actual = actual;
            return Equals(WithoutWhitespace(actual), WithoutWhitespace(expected));
        }

        private static string WithoutWhitespace(object actual)
        {
            if (actual == null) return null;
            StringBuilder stringBuilder = new StringBuilder();
            foreach (char c in actual.ToString()) if (!char.IsWhiteSpace(c)) stringBuilder.Append(c);
            return stringBuilder.ToString();
        }

        public override void WriteDescriptionTo(MessageWriter writer)
        {
            writer.WriteValue(expected);
        }
    }
}